﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Infragistics.Win.UltraWinGrid;
using Infragistics.Win;
using CrystalDecisions.CrystalReports.Engine;

/*
 * Tran Trung Thuc
 * 22/11/2012
 */

namespace POS_NEW
{
    public partial class frmTraHang : Form
    {
        public frmTraHang(int _DoiTuong)
        {
            InitializeComponent();
            KeyPreview = true;
            DoiTuong = _DoiTuong;
        }
        int DoiTuong = 0;
        int DonVi ;
        int tab = 0;
        decimal GiamGia = 0;
        decimal GiamPhanTram = 0;
        DataTable tbHangHoa = null;
        DataTable tbThanhPham = null;
        DataTable tbCombo = null;
        object TuNgay;
        object DenNgay;
        SummarySettings ss;
        string MaPhieu="";
        #region "Tab Tra Hang"
        #region "Load Data"
        private void LoadDataTable_HangHoa()
        {

            if (DoiTuong == 1)
            {
                var colHangHoa = new[] { "Mã Hàng hóa", "Hàng hóa", "Giá Nhập", "Mã đơn vị", "Đơn vị" };
                tbHangHoa = AccessDataLayer.ExecuteDT("spHangHoa_TraHang_Select", CommandType.StoredProcedure, "@Ten_HangHoa", "", "@AmKho", myProgress.AmKho)
                    .DefaultView.ToTable(true, colHangHoa);
            }
            else
            {
                var colHangHoa = new[] { "Mã Hàng hóa", "Hàng hóa", "Giá 1", "Giá 2", "Giá 3", "Mã đơn vị", "Đơn vị" };
                tbHangHoa = AccessDataLayer.ExecuteDT("spHangHoa_TraHang_Select", CommandType.StoredProcedure, "@Ten_HangHoa", "", "@AmKho", myProgress.AmKho)
                    .DefaultView.ToTable(true, colHangHoa);
            }
            DataRow dr = tbHangHoa.NewRow();
            dr["Mã Hàng hóa"] = -1;
            dr["Hàng hóa"] = " ----Chọn mặt hàng----";
            tbHangHoa.Rows.InsertAt(dr, 0);

        }
        private void LoadDataTable_ThanhPham()
        {
            var colThanhPham = new[] { "Mã thành phẩm", "Thành phẩm", "Giá 1", "Giá 2", "Giá 3", "Mã đơn vị", "Đơn vị" };
            tbThanhPham = AccessDataLayer.ExecuteDT("spThanhPham_Select", CommandType.StoredProcedure, "@Ten_ThanhPham", "")
                .DefaultView.ToTable(true, colThanhPham);
            DataRow dr = tbThanhPham.NewRow();
            dr["Mã thành phẩm"] = -1;
            dr["Thành phẩm"] = " ----Chọn thành phẩm----";
            tbThanhPham.Rows.InsertAt(dr,0);
        }
        private void LoadDataTable_Combo()
        {
                         //------------
            var colCombo = new[] { "Mã Set Menu", "Set Menu", "Giá" };
                tbCombo = AccessDataLayer.ExecuteDT("spCombo_Select", CommandType.StoredProcedure, "@Ten_Combo", "")
                    .DefaultView.ToTable(true, colCombo);
                DataRow dr = tbCombo.NewRow();
                dr["Mã Set Menu"] = -1;
                dr["Set Menu"] = " ----Chọn Set Menu----";
                tbCombo.Rows.InsertAt(dr,0);
        }
        private void LoadGridTraHang()
        {
        
            DataTable dt = new DataTable();
            dt.Columns.Add("Mã Hàng hóa");
            dt.Columns.Add("Mã thành phẩm");
            dt.Columns.Add("Mã Set Menu");
            dt.Columns.Add("Hàng hóa");
            dt.Columns.Add("Đơn giá");
            dt.Columns.Add("Số lượng");
            dt.Columns.Add("Thành tiền");
            dt.Columns.Add("Số lô");
            dt.Columns.Add("Mã khuyến mãi");
            dt.Columns.Add("Trạng thái");
            dt.Columns.Add("Mã đơn vị");
            dt.Columns.Add("Đơn vị");
            grdPhieu_TraKH_Chitiet.DataSource = dt;
            grdPhieu_TraKH_Chitiet.CalcManager = ultraCalcManager1;
            grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Mã Hàng hóa"].Hidden = true;
            grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Mã thành phẩm"].Hidden = true;
            grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Mã Set Menu"].Hidden = true;
            grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Mã khuyến mãi"].Hidden = true;
            grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Mã đơn vị"].Hidden = true;
            grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Trạng thái"].Hidden = true;
            grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Đơn vị"].Width = 50;
            grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Thành tiền"].Width = 150;
            grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Thành tiền"].Formula = "[Số lượng] * [Đơn giá]";
            grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Thành tiền"].CellAppearance.TextHAlign = HAlign.Right;
            grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Đơn giá"].CellAppearance.TextHAlign = HAlign.Right;
            NgoaiTeChange();
        }
        private void LoadComboboxKhachHang()
        {
            DataTable dt = new DataTable();
            var colKhachHang = new[] { "Mã khách hàng", "Khách hàng", "Tên tắt", "Phone", "Email", "Ngày sinh" };
                dt = AccessDataLayer.ExecuteDT("spKhachHang_Select", CommandType.StoredProcedure, "@Ten_Tat_KhachHang", "")
                    .DefaultView.ToTable(true,colKhachHang);
                cboKhachHang.ValueMember = "Mã khách hàng";
                cboKhachHang.DisplayMember = "Tên tắt";
                cboKhachHang.DataSource = dt;
                cboKhachHang.DisplayLayout.Bands[0].Columns["Mã khách hàng"].Hidden = true;
                cboKhachHang.Rows[0].Selected= true;
        }
        private void LoadComboboxNhaCungCap()
        {
            DataTable dt = new DataTable();
            var colNhaCungCap = new[] { "Mã", "Nhà cung cấp", "Tên tắt", "Điện thoại", "Email" };
            dt = AccessDataLayer.ExecuteDT("spNhaCungCap_Search", CommandType.StoredProcedure, "@Ten_Tat_NCC", "")
                    .DefaultView.ToTable(true,colNhaCungCap);
                cboKhachHang.ValueMember = "Mã";
                cboKhachHang.DisplayMember = "Tên tắt";
                cboKhachHang.DataSource = dt;
                cboKhachHang.DisplayLayout.Bands[0].Columns["Mã"].Hidden = true;
                cboKhachHang.Rows[0].Selected = true;
        }
        private void LoadComboboxNgoaiTe()
        {
            if (DoiTuong == 0)
            {
                cboNgoaiTe.DataSource = AccessDataLayer.ExecuteDT("spNgoaiTe_Select", CommandType.StoredProcedure, "@Ten_NgoaiTe", "");
                cboNgoaiTe.DisplayLayout.Bands[0].Columns["Mã ngoại tệ"].Hidden = true;
                cboNgoaiTe.DisplayLayout.Bands[0].Columns["Mô tả"].Hidden = true;
            }
        }
        private void LoadComboboxHangHoa()
        {
            LoadDataTable_HangHoa();
            cboHangHoa.DataSource = null;
            cboHangHoa.ValueMember = "Mã Hàng hóa";
            cboHangHoa.DisplayMember = "Hàng hóa";
            cboHangHoa.DataSource = tbHangHoa;
            cboHangHoa.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            cboHangHoa.DisplayLayout.Bands[0].Columns["Mã đơn vị"].Hidden = true;
            if (cboHangHoa.Rows.Count > 0)
                cboHangHoa.Value = -1;
        }
        private void LoadComboboxThanhPham()
        {
            LoadDataTable_ThanhPham();
          
            cboHangHoa.DataSource = null;
            cboHangHoa.ValueMember = "Mã thành phẩm";
            cboHangHoa.DisplayMember = "Thành phẩm";
            cboHangHoa.DataSource = tbThanhPham;
            cboHangHoa.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            cboHangHoa.DisplayLayout.Bands[0].Columns["Mã đơn vị"].Hidden = true;
            if (cboHangHoa.Rows.Count > 0)
                cboHangHoa.Value = -1;
        }
        private void LoadComboboxCombo()
        {
            LoadDataTable_Combo();
            cboHangHoa.DataSource = null;
            cboHangHoa.ValueMember = "Mã Set Menu";
            cboHangHoa.DisplayMember = "Set Menu";
            cboHangHoa.DataSource = tbCombo;
            cboHangHoa.DisplayLayout.Bands[0].Columns[0].Hidden = true;
            if (cboHangHoa.Rows.Count > 0)
                cboHangHoa.Value = -1;
        }
        private void LapPhieu_KhachHang()
        {
            DoiTuong = 0;
            ultraGroupBox1.Text = "Khách hàng trả hàng";
            dtNgayTra.Select();
            dtNgayTra.SelectAll();
            lblF1_Info.Visible = true;
            lblKhachHang.Text = "Khách hàng :";
            lblNgoaiTe.Visible = true;
            cboNgoaiTe.Visible = true;
            txtGiamGia.Enabled = true;
            lblGiamGia.Text = "Giảm % :";
            GiamGia = decimal.Parse(txtGiamGia.Value.ToString());
            GiamPhanTram = 0;
            lbelGiam.Visible = true;
             
            LoadComboboxHangHoa();
            LoadComboboxKhachHang();
            LoadComboboxNgoaiTe();

            UltraGridBand band = this.grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0];
            if (band.Summaries.Count > 0)
            {
                band.Summaries.RemoveAt(0);
            }
            this.ResetControl();
            LoadGridTraHang();
        }
        private void LapPhieu_NhaCungCap()
        {
            DoiTuong = 1;
            ultraGroupBox1.Text = "Trả hàng nhà cung cấp";
            dtNgayTra.Select();
            dtNgayTra.SelectAll();
            lblF1_Info.Visible = false;           
            lblKhachHang.Text = "Nhà cung cấp :";
            lblNgoaiTe.Visible = false;
            cboNgoaiTe.Visible = false;
            txtGiamGia.Enabled = false;
            txtGiamGia.ResetValue();
            lbelGiam.Visible = false;

            LoadComboboxHangHoa();
            LoadComboboxNhaCungCap();

            lblHangHoa.Text = "Hàng hóa :";

            UltraGridBand band = this.grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0];
            if (band.Summaries.Count > 0)
            {
                band.Summaries.RemoveAt(0);
            }
            this.ResetControl();
            LoadGridTraHang();
        }
        #endregion
        #region "Save Data"
        private void SavetoGridKH(string ValueMember, object Value, string Ten_HangHoa, string SoLo, double DonGia, int ID_KhuyenMai, int status, float SoLuong)
        {
            foreach (UltraGridRow row in this.grdPhieu_TraKH_Chitiet.Rows)
            {
                if (row.Cells[ValueMember].Value.ToString().Trim()==Value.ToString().Trim())
                {
                    using (ConfirmScreen cfs = new ConfirmScreen("Đã nhập '" + Ten_HangHoa + "' \n Bạn có muốn cộng dồn vào số lượng trước đó ?"))
                    {
                        if (cfs.ShowDialog() == DialogResult.OK)
                        {
                            double t = double.Parse(row.Cells["Số lượng"].Value.ToString()) + SoLuong;
                            row.Cells["Số lượng"].Value = t;
                            row.Cells["Thành tiền"].Value = t * DonGia;
                            return;
                        }
                        else
                            return;
                    }
                }

            }
            if (SoLo == "")
                SoLo = "01012011001";
            UltraGridRow urow = grdPhieu_TraKH_Chitiet.Rows.Band.AddNew();
            urow.Cells[ValueMember].Value = Value;
            urow.Cells["Hàng hóa"].Value = Ten_HangHoa;
            urow.Cells["Số lượng"].Value = SoLuong;
            urow.Cells["Đơn giá"].Value = DonGia;
            
            urow.Cells["Mã khuyến mãi"].Value = ID_KhuyenMai;
            urow.Cells["Trạng thái"].Value = status;
            urow.Cells["Số lô"].Value = SoLo;
            urow.Cells["Mã đơn vị"].Value = DonVi;
            urow.Cells["Đơn vị"].Value = txtDonVi.Text;
            grdPhieu_TraKH_Chitiet.PerformAction(UltraGridAction.CommitRow);
            btnHuy.Enabled = true;
            btnXuatPhieu.Enabled = true;
        }
        private int SaveData()
        {
            int kq = 0;
            if (DoiTuong == 0)
            {
                DataTable tbPhieu_TraKH_Chitiet = new DataTable();
                var colPhieu_TraKH_Chitiet = new[] { "Mã Hàng hóa", "Mã thành phẩm", "Mã Set Menu", "Số lô", "Đơn giá", "Thành tiền", "Mã khuyến mãi", "Trạng thái", "Số lượng" };
                tbPhieu_TraKH_Chitiet = ((DataTable)grdPhieu_TraKH_Chitiet.DataSource).DefaultView.ToTable(true, colPhieu_TraKH_Chitiet);
                kq = AccessDataLayer.ExecuteNonQuery("spPhieu_TraKH_Insert",
                    "@output",ref MaPhieu,
                  CommandType.StoredProcedure,
                 "@ID_KhachHang", cboKhachHang.Value,
                 "@ID_ChiNhanh", myProgress.ID_ChiNhanh,
                 "@ID_NgoaiTe", cboNgoaiTe.Value,
                 "@NgayTra", dtNgayTra.DateTime,
                 "@NgayLamViec", myProgress.NgayLamViec,
                 "@TongTien", txtTongTien.Value,
                 "@GiamGia", GiamGia,
                 "@Giam_PhanTram", GiamPhanTram,
                 "@ID_KhuVuc_Chitiet", "1",
                 "@GhiChu", txtGhiChu.Text,
                 "@TinhTrang", myProgress.TinhTrang,
                 "@PrintCount", 1,
                 "@ID_NhanVien", myProgress.ID_NhanVien,
                 "@tbPhieu_TraKH_CT", tbPhieu_TraKH_Chitiet
             );

            }
            else
            {
                DataTable tbPhieu_TraNCC_Chitiet = new DataTable();
                var colPhieu_TraNCC_Chitiet = new[] { "Mã Hàng hóa", "Số lô", "Số lượng", "Đơn giá", "Thành tiền", "Trạng thái" };
                tbPhieu_TraNCC_Chitiet = ((DataTable)grdPhieu_TraKH_Chitiet.DataSource).DefaultView.ToTable(true, colPhieu_TraNCC_Chitiet);
                kq = AccessDataLayer.ExecuteNonQuery("spPhieu_TraNCC_Insert",
                "@output", ref MaPhieu,
                CommandType.StoredProcedure,
                "ID_NhaCungCap", cboKhachHang.Value,
                "@ID_ChiNhanh", myProgress.ID_ChiNhanh,
                "@NgayTra", dtNgayTra.DateTime,
                "@NgayLamViec", myProgress.NgayLamViec,
                "@TongTien", txtTongTien.Value,
                "@GhiChu", txtGhiChu.Text,
                "@TinhTrang", myProgress.TinhTrang,
                "@PrintCount", 1,
                "@ID_Kho", myProgress.Kho,
                "@ID_NhanVien", myProgress.ID_NhanVien,
                "@tbPhieu_TraNCC_CT", tbPhieu_TraNCC_Chitiet
                );
            }
            return kq;

        }
        #endregion
        #region "Other Methods"
        private void ChangeType_HangHoa()
        {
            cboHangHoa.Value = -1;
            if (lblHangHoa.Text == "Set Menu :")
            {
                lblHangHoa.Text = "Hàng hóa :";
                LoadComboboxHangHoa();
            }
            else if (lblHangHoa.Text == "Hàng hóa :")
            {
                lblHangHoa.Text = "Thành phẩm :";
                LoadComboboxThanhPham();
            }
            else
            {
                lblHangHoa.Text = "Set Menu :";
                LoadComboboxCombo();
            }
            cboHangHoa.Focus();
        }
        private void ResetControl()
        {
            txtSoLo.ResetText();
            txtGhiChu.ResetText();
            cboNgoaiTe.ResetText();
            txtGiamGia.ResetValue();
            txtSoLuong.Value=1;
            txtDonGia.ResetValue();
            txtTongTien.ResetValue();
            btnXuatPhieu.Enabled = false;
            btnXoa.Enabled = false;
            btnHuy.Enabled = false;
            grdPhieu_TraKH_Chitiet.DisplayLayout.Override.SelectTypeRow = SelectType.Default;
            grdPhieu_TraKH_Chitiet.Selected.Rows.AddRange((UltraGridRow[])grdPhieu_TraKH_Chitiet.Rows.All);
            grdPhieu_TraKH_Chitiet.DeleteSelectedRows(false);
            cboKhachHang.Focus();
            NgoaiTeChange();
        }
        private void NgoaiTeChange()
        {
            string NgoaiTe = "vi-VN";
            if (cboNgoaiTe.Text == "" || !cboNgoaiTe.Enabled)
            {
                NgoaiTe = "vi-VN";
            }
            else
            {
                if (cboNgoaiTe.IsItemInList(cboNgoaiTe.Text))
                {
                   NgoaiTe = cboNgoaiTe.DisplayLayout.Rows[cboNgoaiTe.ActiveRow.Index].Cells["Mô tả"].Value.ToString();
                }
            }
            UltraGridBand band = this.grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0];
            if (band.Summaries.Count > 0)
            {
                band.Summaries.RemoveAt(0);
            }
            if (band.Columns.Exists("Thành tiền"))
            {
                System.Globalization.CultureInfo ci = new System.Globalization.CultureInfo(NgoaiTe);
                ss = band.Summaries.Add(SummaryType.Sum, band.Columns["Thành tiền"], SummaryPosition.UseSummaryPositionColumn);
                txtTongTien.FormatProvider = txtDonGia.FormatProvider = txtGiamGia.FormatProvider = ci;
                ss.Appearance.FontData.Bold = Infragistics.Win.DefaultableBoolean.True;
                //ss.DisplayFormat = "TC:{0:C}";
                ss.DisplayFormat = " ";
                ss.DisplayFormatProvider = ci;
                ss.Appearance.TextHAlign = HAlign.Right;
            }
            grdPhieu_TraKH_Chitiet.DisplayLayout.Override.SummaryFooterCaptionVisible = DefaultableBoolean.False;
        }
        #endregion
        #region "Controls Event"
        private void dtNgayTra_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                if (cboNgoaiTe.Visible)
                    cboNgoaiTe.Focus();
                else
                    txtGhiChu.Focus();
            }
        }
        private void cboNgoaiTe_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                try
                {
                    NgoaiTeChange();
                    txtGhiChu.Focus();
                }
                catch (Exception ex)
                {
                    using (ErrorScreen er = new ErrorScreen(ex.Message))
                    {
                        er.ShowDialog();
                    }
                }

            }
        }
        private void txtGhiChu_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                cboKhachHang.Focus();
            }
        }
        private void cboKhachHang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                if (cboKhachHang.IsItemInList(cboKhachHang.Text))
                    if (txtGiamGia.Enabled)
                        txtGiamGia.Focus();
                    else
                        cboHangHoa.Focus();
            }
        }
        private void txtGiamGia_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                if (lblGiamGia.Text == "Giảm giá :")
                {
                    GiamGia = decimal.Parse(txtGiamGia.Value.ToString());
                    GiamPhanTram = 0;
                }
                else
                {
                    GiamGia = 0;
                    GiamPhanTram = decimal.Parse(txtGiamGia.Value.ToString());
                }
                cboHangHoa.Focus();
            }
            else if (e.KeyData == Keys.F1)
            {
                if (lblGiamGia.Text == "Giảm giá :")
                {
                    lblGiamGia.Text = "Giảm % :";
                }
                else
                {
                    lblGiamGia.Text = "Giảm giá :";

                }
            }
        }
        private void txtGiamPhantram_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                cboHangHoa.Focus();
        }
        private void cboHangHoa_KeyDown(object sender, KeyEventArgs e)
        {

            if (e.KeyData == Keys.F1)
            {
                if (DoiTuong == 0)
                    ChangeType_HangHoa();
            }
            if (e.KeyData == Keys.Enter)
            {
               if (cboHangHoa.ActiveRow != null)
                   if (cboHangHoa.IsItemInList(cboHangHoa.Text)
                       && cboHangHoa.Text != " ----Chọn mặt hàng----"
                       && cboHangHoa.Text != " ----Chọn thành phẩm----"
                       && cboHangHoa.Text != " ----Chọn Set Menu----"
                       )
                {

                    try
                    {
                        txtDonGia.Value = decimal.Parse(((DataTable)cboHangHoa.DataSource).Rows[cboHangHoa.ActiveRow.Index][2].ToString());
                        
                        if (cboHangHoa.Text != "")
                        {
                            if (lblHangHoa.Text != "Set Menu :")
                            {
                                txtDonVi.Text = (((DataTable)cboHangHoa.DataSource).Rows[cboHangHoa.ActiveRow.Index]["Đơn vị"].ToString());
                                if (((DataTable)cboHangHoa.DataSource).Rows[cboHangHoa.ActiveRow.Index]["Mã đơn vị"] != null &&
                                    ((DataTable)cboHangHoa.DataSource).Rows[cboHangHoa.ActiveRow.Index]["Mã đơn vị"].ToString() != "")
                                    DonVi = int.Parse(((DataTable)cboHangHoa.DataSource).Rows[cboHangHoa.ActiveRow.Index]["Mã đơn vị"].ToString());
                            }
                            else
                                txtDonVi.Text = "";
                        }
                        txtSoLuong.Select();
                    }
                    catch (Exception ex)
                    {
                        using (ErrorScreen er = new ErrorScreen(ex.Message))
                        {
                            er.ShowDialog();
                        }
                    }
                }
            }
        }
        private void txtSoLuong_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                if (float.Parse(txtSoLuong.Value.ToString()) > 0)
                {
                    if (!txtSoLo.Enabled)
                        txtDonGia.Focus();
                    else
                        txtSoLo.Focus();
                }
            }
        }
        private void txtSoLo_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
                txtDonGia.Focus();
        }
        private void txtDonGia_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                if (txtDonGia.Value != 0
                       && cboKhachHang.IsItemInList(cboKhachHang.Text)
                       && cboHangHoa.IsItemInList(cboHangHoa.Text) )
                {
                    this.SavetoGridKH(cboHangHoa.ValueMember, cboHangHoa.Value, cboHangHoa.Text,
                        txtSoLo.Text, double.Parse(txtDonGia.Value.ToString()), 1, 1, float.Parse(txtSoLuong.Value.ToString()));

                    cboHangHoa.Focus();

                    this.grdPhieu_TraKH_Chitiet.DisplayLayout.PerformAutoResizeColumns(true, PerformAutoSizeType.VisibleRows);
                    grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Đơn vị"].Width = 50;
                    grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Trạng thái"].Width = 50;
                    grdPhieu_TraKH_Chitiet.DisplayLayout.Bands[0].Columns["Thành tiền"].Width = 100;
                }
            }
        }
        private void grdPhieu_TraKH_Chitiet_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Delete)
            {
                if (grdPhieu_TraKH_Chitiet.Rows.Count > 0)
                {
                    if (grdPhieu_TraKH_Chitiet.ActiveRow != null)
                        if (grdPhieu_TraKH_Chitiet.ActiveRow.Selected)
                        {
                            grdPhieu_TraKH_Chitiet.ActiveRow.Delete(false);
                        }
                }
            }
        }
        

        private void cboNgoaiTe_Leave(object sender, EventArgs e)
        {
            if (!cboNgoaiTe.IsItemInList(cboNgoaiTe.Text) && cboNgoaiTe.Text != "")
            {
                using (ErrorScreen er = new ErrorScreen("Nhập đúng ngoại tệ hoặc để trống !", "Thông báo", 4))
                {
                    er.ShowDialog();
                    cboNgoaiTe.Focus();
                    cboNgoaiTe.SelectAll();
                }
            }
            else if (cboNgoaiTe.IsItemInList(cboNgoaiTe.Text))
            {
                try
                {
                    NgoaiTeChange();
                    txtGhiChu.Focus();
                }
                catch (Exception ex)
                {
                    using (ErrorScreen er = new ErrorScreen(ex.Message))
                    {
                        er.ShowDialog();
                    }
                }
            }
        }
        private void cboKhachHang_Leave(object sender, EventArgs e)
        {
            if (!cboKhachHang.IsItemInList(cboKhachHang.Text) && cboKhachHang.Text != "")
            {
                string s = "khách hàng";
                if (DoiTuong == 1)
                    s = "nhà cung cấp";
                using (ErrorScreen er = new ErrorScreen("Vui lòng nhập đúng tên " + s + " !", "Thông báo", 4))
                {
                    er.ShowDialog();
                    cboKhachHang.Focus();
                    cboKhachHang.SelectAll();
                }
            }
        }
        private void txtGiamGia_Leave(object sender, EventArgs e)
        {
            if (lblGiamGia.Text == "Giảm giá :")
            {
                GiamGia = decimal.Parse(txtGiamGia.Value.ToString());
                GiamPhanTram = 0;
            }
            else
            {
                GiamGia = 0;
                GiamPhanTram = decimal.Parse(txtGiamGia.Value.ToString());
            }
        }
     
        
        private void txtSoLuong_Enter(object sender, EventArgs e)
        {
            txtSoLuong.SelectAll();
        }
        private void txtDonGia_Enter(object sender, EventArgs e)
        {
            txtDonGia.SelectAll();
        }

        private void lblGiamGia_TextChanged(object sender, EventArgs e)
        {
            if (lblGiamGia.Text == "Giảm % :")
            {
                txtGiamGia.MaxValue = 100;
            }
            else
            {
                txtGiamGia.MaxValue = 2000000000;
            }
        }       
        private void grdPhieu_TraKH_Chitiet_SummaryValueChanged(object sender, SummaryValueChangedEventArgs e)
        {
            txtTongTien.Value=decimal.Parse( grdPhieu_TraKH_Chitiet.DisplayLayout.Bands.Layout.Rows.SummaryValues[0].Value.ToString());
            if (grdPhieu_TraKH_Chitiet.Rows.Count > 0)
            {
                if (grdPhieu_TraKH_Chitiet.ActiveRow == null)
                {
                    btnXoa.Enabled = false;
                }
            }
            else
            {
                btnXoa.Enabled = false;
                btnXuatPhieu.Enabled = false;
            }
        }
        
        private void grdPhieu_TraKH_Chitiet_BeforeCellActivate(object sender, CancelableCellEventArgs e)
        {
            e.Cell.Activation = Activation.NoEdit;
        }
        private void grdPhieu_TraKH_Chitiet_InitializeRow(object sender, InitializeRowEventArgs e)
        {
                NgoaiTeChange();
        }
        private void grdPhieu_TraKH_Chitiet_ClickCell(object sender, ClickCellEventArgs e)
        {
            if (grdPhieu_TraKH_Chitiet.Rows.Count > 0)
            {
                if (grdPhieu_TraKH_Chitiet.ActiveRow != null)
                {
                    if (grdPhieu_TraKH_Chitiet.Focused)
                    {
                        btnXoa.Enabled = true;
                        grdPhieu_TraKH_Chitiet.Rows[grdPhieu_TraKH_Chitiet.ActiveRow.Index].Selected = true;
                        grdPhieu_TraKH_Chitiet.DisplayLayout.Override.SelectTypeRow = SelectType.Single;
                    }
                }
            }
        }
        private void btnXuatPhieu_Click(object sender, EventArgs e)
        {
            string kh = "";
            if (DoiTuong == 0)
                kh = "khách hàng";
            else
                kh = "nhà cung cấp";
            if (cboKhachHang.Text.Trim() == "") 
            {
                using (ErrorScreen ers = new ErrorScreen("Vui lòng nhập tên " + kh + "!", "Thông báo", 3))
                    ers.ShowDialog();
                return;
            }
            try
            {
                if (SaveData() > 0)
                {
                    if (DoiTuong == 0)
                    {
                        DataSet ds = new DataSet();
                        DataTable tbPhieu_TraKH =
                            AccessDataLayer.ExecuteDT("spPhieu_TraKH_Select", CommandType.StoredProcedure
                                                       , "@Ten_Tat_KhachHang", ""
                                                       , "@TuNgay", dtNgayTra.Value
                                                       , "@DenNgay", dtNgayTra.Value);
                        tbPhieu_TraKH.TableName = "tbPhieu_TraKH";
                        DataTable tbPhieu_TraKH_Chitiet =
                            AccessDataLayer.ExecuteDT("spPhieu_TraKH_Chitiet_Select", CommandType.StoredProcedure
                            , "@Ma_PhieuTra_KH", MaPhieu);
                        tbPhieu_TraKH_Chitiet.TableName = "tbPhieu_TraKH_Chitiet";
                        ds.Tables.Add(tbPhieu_TraKH.Copy());
                        ds.Tables.Add(tbPhieu_TraKH_Chitiet.Copy());
                        this.ResetControl();
                        report.rptKhachHang_TraHang rpt = new report.rptKhachHang_TraHang();
                        //ReportDocument rpt = new ReportDocument();
                        //rpt.Load(Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("bin")) + @"\report\rptKhachHang_TraHang.rpt");
                        rpt.SetDataSource(ds);
                        myProgress.SubReportHeader(rpt);
                        using (frmDisplayReport frm = new frmDisplayReport(rpt))
                        {
                            if (frm.ShowDialog() == DialogResult.Cancel)
                                rpt.Dispose();
                        }
                    }
                    else
                    {
                        DataSet ds = new DataSet();
                        DataTable tbPhieu_TraNCC =
                            AccessDataLayer.ExecuteDT("spPhieu_TraNCC_Select", CommandType.StoredProcedure
                                                       , "@Ten_Tat_NCC", ""
                                                       , "@TuNgay", dtNgayTra.Value
                                                       , "@DenNgay", dtNgayTra.Value);
                        tbPhieu_TraNCC.TableName = "tbPhieu_TraNCC";
                        DataTable tbPhieu_TraNCC_Chitiet =
                            AccessDataLayer.ExecuteDT("spPhieu_TraNCC_Chitiet_Select", CommandType.StoredProcedure
                            , "@Ma_PhieuTra_NCC", MaPhieu);
                        tbPhieu_TraNCC_Chitiet.TableName = "tbPhieu_TraNCC_Chitiet";
                        ds.Tables.Add(tbPhieu_TraNCC.Copy());
                        ds.Tables.Add(tbPhieu_TraNCC_Chitiet.Copy());
                        this.ResetControl();
                        report.rptTraHang_NCC rpt = new report.rptTraHang_NCC();
                        //ReportDocument rpt = new ReportDocument();
                        //rpt.Load(Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("bin")) + @"\report\rptTraHang_NCC.rpt");
                        rpt.SetDataSource(ds);
                        myProgress.SubReportHeader(rpt);
                        using (frmDisplayReport frm = new frmDisplayReport(rpt))
                        {
                            if (frm.ShowDialog() == DialogResult.Cancel)
                                rpt.Dispose();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                using (ErrorScreen er = new ErrorScreen(ex.Message))
                {
                    er.ShowDialog();
                }
            }
        
        }
        
        private void btnXoa_Click(object sender, EventArgs e)
        {
            if (grdPhieu_TraKH_Chitiet.Rows.Count > 0)
            {
                if (grdPhieu_TraKH_Chitiet.ActiveRow != null)
                    if (grdPhieu_TraKH_Chitiet.ActiveRow.Selected)
                    {
                        grdPhieu_TraKH_Chitiet.ActiveRow.Delete(false);
                    }
            }
        }
        private void btnHuy_Click(object sender, EventArgs e)
        {
            using (ConfirmScreen cfs = new ConfirmScreen("Bạn có muốn hủy tất cá các thông tin vừa nhập ?"))
            {
                if (cfs.ShowDialog() == DialogResult.OK)
                    this.ResetControl();
                else
                    return;
            }

        }
        private void btnThoat_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion
        #endregion
        #region "Tab Lich Su"
        #region " Load Data"
        private void LoadLichSu_Phieu_TraHang()
        {
            if (DoiTuong == 1)
            {
                grdPhieuTraHang.DataSource = AccessDataLayer.ExecuteDT("spPhieu_TraNCC_Select", CommandType.StoredProcedure
                , "@Ten_Tat_NCC", ""
               , "@TuNgay",DateTime.Today
                , "@DenNgay", DateTime.Today); 
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Mã nhà cung cấp"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Mã chi nhánh"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Chi nhánh"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Ngày làm việc"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Mã kho"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Mã nhân viên"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["PrintCount"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Kho"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.PerformAutoResizeColumns(true, PerformAutoSizeType.VisibleRows);
            }
            else
            {
                grdPhieuTraHang.DataSource = AccessDataLayer.ExecuteDT("spPhieu_TraKH_Select", CommandType.StoredProcedure
                   , "@Ten_Tat_KhachHang", ""
                  , "@TuNgay", DateTime.Today
                   , "@DenNgay", DateTime.Today);
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Mã khách hàng"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Mã thẻ trả trước"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Thẻ trả trước"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Mã chi nhánh"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Chi nhánh"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Mã ngoại tệ"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Mã khu vực chi tiết"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Mã nhân viên"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["PrintCount"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Tình trạng"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Ngày làm việc"].Hidden = true;
                grdPhieuTraHang.DisplayLayout.PerformAutoResizeColumns(true, PerformAutoSizeType.VisibleRows);
            }
            gridPhieuTra_Chitiet.DataSource = null;
            //grdPhieuTraHang.DisplayLayout.AutoFitStyle= AutoFitStyle.ResizeAllColumns;
            grdPhieuTraHang.DisplayLayout.Bands[0].Columns["Ngày trả"].Format = "dd/MM/yyyy";
        }
        private void LoadLichSu_PhieuTra_Chitiet()
        {
            if (DoiTuong == 1)
            {
                grdPhieuTraHang.Rows[grdPhieuTraHang.ActiveRow.Index].Selected = true;
                gridPhieuTra_Chitiet.DataSource = AccessDataLayer.ExecuteDT("spPhieu_TraNCC_Chitiet_Select", CommandType.StoredProcedure, "@Ma_PhieuTra_NCC", grdPhieuTraHang.ActiveRow.Cells[0].Value);
            }
            else
            {
                grdPhieuTraHang.Rows[grdPhieuTraHang.ActiveRow.Index].Selected = true;
                gridPhieuTra_Chitiet.DataSource = AccessDataLayer.ExecuteDT("spPhieu_TraKH_Chitiet_Select", CommandType.StoredProcedure, "@Ma_PhieuTra_KH", grdPhieuTraHang.ActiveRow.Cells[0].Value);
                gridPhieuTra_Chitiet.DisplayLayout.Bands[0].Columns["Mã thành phẩm"].Hidden = true;
                gridPhieuTra_Chitiet.DisplayLayout.Bands[0].Columns["Mã Set Menu"].Hidden = true;
                gridPhieuTra_Chitiet.DisplayLayout.Bands[0].Columns["Mã khuyến mãi"].Hidden = true;
                gridPhieuTra_Chitiet.DisplayLayout.Bands[0].Columns["Khuyến mãi"].Hidden = true;
            }
            gridPhieuTra_Chitiet.DisplayLayout.Bands[0].Columns["STT"].Hidden = true;
            gridPhieuTra_Chitiet.DisplayLayout.Bands[0].Columns["Mã phiếu trả"].Hidden = true;
            gridPhieuTra_Chitiet.DisplayLayout.Bands[0].Columns["Barcode"].Hidden = true;
            gridPhieuTra_Chitiet.DisplayLayout.Bands[0].Columns["Mã Hàng hóa"].Hidden = true;
            gridPhieuTra_Chitiet.DisplayLayout.Bands[0].Columns["Mã đơn vị"].Hidden = true;
            gridPhieuTra_Chitiet.DisplayLayout.Bands[0].Columns["Số lô"].Hidden = true;
            gridPhieuTra_Chitiet.DisplayLayout.Bands[0].Columns["Trạng thái"].Hidden = true;
            gridPhieuTra_Chitiet.DisplayLayout.AutoFitStyle = AutoFitStyle.ResizeAllColumns;
            this.gridPhieuTra_Chitiet.DisplayLayout.Override.AllowDelete = Infragistics.Win.DefaultableBoolean.False;
        }
        private void LoadLichSu_KhachHang()
        {
            DoiTuong = 0;
            ultraGroupBox1.Text = "Khách hàng trả hàng";
            lblDoiTuong.Text = "Khách hàng :";
            LoadLichSu_Phieu_TraHang();
        }
        private void LoadLichSu_NhaCungCap()
        {
            DoiTuong = 1;
            ultraGroupBox1.Text = "Trả hàng nhà cung cấp";
            lblDoiTuong.Text = "Nhà cung cấp :";
            LoadLichSu_Phieu_TraHang();
        }
        #endregion
        #region "Search Data"
        private void Seacrh(string ID_DoiTuong,object dtTu,object dtDen)
        {
            //string ID_DoiTuong = "";
            ID_DoiTuong = ID_DoiTuong.Trim();
            if (DoiTuong == 1)
            {
                grdPhieuTraHang.DataSource = AccessDataLayer.ExecuteDT("spPhieu_TraNCC_Select", CommandType.StoredProcedure
              , "@Ten_Tat_NCC", ID_DoiTuong, "@TuNgay", dtTu, "@DenNgay", dtDen);
            }
            else
            {
                grdPhieuTraHang.DataSource = AccessDataLayer.ExecuteDT("spPhieu_TraKH_Select", CommandType.StoredProcedure
           , "@Ten_Tat_KhachHang", ID_DoiTuong, "@TuNgay", dtTu, "@DenNgay", dtDen);
            }
                    gridPhieuTra_Chitiet.DataSource = null;
            
        }
        #endregion
        #region "Delete Data"
        private int DeleteLichSu_Phieu_TraHang(string MaPhieu)
        {
            if (DoiTuong == 1)
            {
                int kq = AccessDataLayer.ExecuteNonQuery("spPhieu_TraNCC_Delete", CommandType.StoredProcedure, "@Ma_PhieuTra_NCC", MaPhieu, "@ID_NhanVien_Xoa",myProgress.ID_NhanVien);
                return kq;
            }
            else
            {
                int kq = AccessDataLayer.ExecuteNonQuery("spPhieu_TraKH_Delete", CommandType.StoredProcedure, "@Ma_PhieuTra_KH", MaPhieu, "@ID_NhanVien_Xoa", myProgress.ID_NhanVien);
                return kq;
            }
        }
        #endregion
        #region "Other Methods"
        private void SetControl_LichSu()
        {
            dtTuNgay.Focus();
            dtTuNgay.SelectAll();
            dtTuNgay.DateTime = DateTime.Today;
            dtDenNgay.DateTime = DateTime.Today;
        }
        #endregion
        #region "Controls Event"
        private void grdPhieuTraHang_ClickCell(object sender, ClickCellEventArgs e)
        {
            if (grdPhieuTraHang.Rows.Count > 0)
            {
                if (grdPhieuTraHang.ActiveRow != null && grdPhieuTraHang.Focus())
                {
                    btXuatLai.Enabled = true;
                    this.LoadLichSu_PhieuTra_Chitiet();
                }
                else
                    btXuatLai.Enabled = false;
            }
            else
                btXuatLai.Enabled = false;
        }
        private void grdPhieuTraHang_AfterCellActivate(object sender, EventArgs e)
        {
            if (grdPhieuTraHang.Rows.Count > 0)
                if (grdPhieuTraHang.ActiveRow != null)
                {
                    this.LoadLichSu_PhieuTra_Chitiet();
                }
        }
        private void grdPhieuTraHang_BeforeCellActivate(object sender, CancelableCellEventArgs e)
        {
            e.Cell.Activation = Activation.NoEdit;
        }
        private void grdPhieuTraHang_InitializeLayout(object sender, InitializeLayoutEventArgs e)
        {
            grdPhieuTraHang.DisplayLayout.PerformAutoResizeColumns(true, PerformAutoSizeType.AllRowsInBand);
            if (grdPhieuTraHang.Rows.Count > 0)
            {
                if (grdPhieuTraHang.ActiveRow != null && grdPhieuTraHang.Focus())
                {
                    btXuatLai.Enabled = true;
                    this.LoadLichSu_PhieuTra_Chitiet();
                }
                else
                    btXuatLai.Enabled = false;
            }
            else
                btXuatLai.Enabled = false;
        }
        private void gridPhieuTra_Chitiet_BeforeCellActivate(object sender, CancelableCellEventArgs e)
        {
            e.Cell.Activation = Activation.NoEdit;

        }
        private void dtTuNgay_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                dtDenNgay.Focus();
                dtDenNgay.SelectAll();   
            }
        }
        private void dtTuNgay_ValueChanged(object sender, EventArgs e)
        {
            TuNgay=dtTuNgay.Value;
            DenNgay=dtDenNgay.Value;
            this.Seacrh(txtDoiTuong.Text,TuNgay,DenNgay);
        }
        private void dtDenNgay_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                    txtDoiTuong.Focus();
                    txtDoiTuong.SelectAll();
            }
        }
        private void dtTuNgay_Enter(object sender, EventArgs e)
        {
            dtTuNgay.SelectAll();
        }       
        private void dtDenNgay_ValueChanged(object sender, EventArgs e)
        {
            TuNgay = dtTuNgay.Value;
            DenNgay = dtDenNgay.Value;
            this.Seacrh(txtDoiTuong.Text, TuNgay, DenNgay);
        }
        private void dtDenNgay_Enter(object sender, EventArgs e)
        {
            dtDenNgay.SelectAll();
        }
        private void txtDoiTuong_TextChanged(object sender, EventArgs e)
        {
            this.Seacrh(txtDoiTuong.Text,TuNgay,DenNgay);
        }
        private void btSearchAll_Click(object sender, EventArgs e)
        {
            txtDoiTuong.ResetText();
            dtTuNgay.DateTime = DateTime.Today;
            dtDenNgay.DateTime = DateTime.Today;
            TuNgay = null;
            DenNgay = null;
            if (DoiTuong == 1)
            {
                grdPhieuTraHang.DataSource = AccessDataLayer.ExecuteDT("spPhieu_TraNCC_Select", CommandType.StoredProcedure
             , "@Ten_Tat_NCC", txtDoiTuong.Text
            , "@TuNgay", TuNgay
             , "@DenNgay", DenNgay);
            }
            else
            {
                grdPhieuTraHang.DataSource = AccessDataLayer.ExecuteDT("spPhieu_TraKH_Select", CommandType.StoredProcedure
                  , "@Ten_Tat_KhachHang",txtDoiTuong.Text
                 , "@TuNgay", TuNgay
                  , "@DenNgay",DenNgay);
            }
        }
        private void btXuatLai_Click(object sender, EventArgs e)
        {
            if (DoiTuong == 1)
            {
                if (grdPhieuTraHang.ActiveRow != null)
                if (grdPhieuTraHang.ActiveRow.Cells[0].Value != null)

                    try
                    {
                        DataSet ds = new DataSet();
                        DataTable dtPhieuTraNCC = ((DataTable)grdPhieuTraHang.DataSource);
                        dtPhieuTraNCC.TableName = "tbPhieu_TraNCC";
                        DataTable dtPhieuTraNCC_Chitiet = ((DataTable)gridPhieuTra_Chitiet.DataSource);
                        dtPhieuTraNCC_Chitiet.TableName = "tbPhieu_TraNCC_Chitiet";
                        ds.Tables.Add(dtPhieuTraNCC.Copy());
                        ds.Tables.Add(dtPhieuTraNCC_Chitiet.Copy());
                        //report.rptTraHang_NCC rpt = new report.rptTraHang_NCC();
                        ReportDocument rpt = new ReportDocument();
                        rpt.Load(Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("bin")) + @"\report\rptTraHang_NCC.rpt");
                        rpt.SetDataSource(ds);
                        myProgress.SubReportHeader(rpt);
                        using (frmDisplayReport frm = new frmDisplayReport(rpt))
                        {
                            if (frm.ShowDialog() == DialogResult.Cancel)
                                rpt.Dispose();
                        }


                    }
                    catch (Exception ex)
                    {
                        using (ErrorScreen ers = new ErrorScreen(ex.Message, 4))
                        {
                            ers.ShowDialog();
                            return;
                        }
                    }
            }
            else
            {
                if (grdPhieuTraHang.ActiveRow.Cells[0].Value != null)

                    try
                    {
                        DataSet ds = new DataSet();
                        DataTable dtPhieuTraKH = ((DataTable)grdPhieuTraHang.DataSource);
                        dtPhieuTraKH.TableName = "tbPhieu_TraKH";
                        DataTable dtPhieuTraKH_Chitiet = ((DataTable)gridPhieuTra_Chitiet.DataSource);
                        dtPhieuTraKH_Chitiet.TableName = "tbPhieu_TraKH_Chitiet";
                        ds.Tables.Add(dtPhieuTraKH.Copy());
                        ds.Tables.Add(dtPhieuTraKH_Chitiet.Copy());
                        report.rptKhachHang_TraHang rpt = new report.rptKhachHang_TraHang();
                        //ReportDocument rpt = new ReportDocument();
                        //rpt.Load(Application.ExecutablePath.Substring(0, Application.ExecutablePath.LastIndexOf("bin")) + @"\report\rptKhachHang_TraHang.rpt");
                        rpt.SetDataSource(ds);
                        myProgress.SubReportHeader(rpt);
                        using (frmDisplayReport frm = new frmDisplayReport(rpt))
                        {
                            if (frm.ShowDialog() == DialogResult.Cancel)
                                rpt.Dispose();
                        }


                    }
                    catch (Exception ex)
                    {
                        using (ErrorScreen ers = new ErrorScreen(ex.Message, 4))
                        {
                            ers.ShowDialog();
                            return;
                        }
                    }
            }
        }
        private void grdPhieuTraHang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Delete)
            {
                if (grdPhieuTraHang.Rows.Count > 0)
                    if (grdPhieuTraHang.ActiveRow != null)
                    {
                        using (ConfirmScreen cfs = new ConfirmScreen("Xóa phiếu  " + grdPhieuTraHang.ActiveRow.Cells[0].Value.ToString() + " ?"))
                        {
                            if (cfs.ShowDialog() == DialogResult.OK)
                            {
                                try
                                {
                                    if (this.DeleteLichSu_Phieu_TraHang(grdPhieuTraHang.ActiveRow.Cells[0].Value.ToString()) > 0)
                                    {
                                        using (ErrorScreen er = new ErrorScreen("Đã xóa phiếu " + grdPhieuTraHang.ActiveRow.Cells[0].Value.ToString(), "Thông Báo", 4))
                                        {
                                            er.ShowDialog();
                                            grdPhieuTraHang.DeleteSelectedRows(false);
                                            gridPhieuTra_Chitiet.DataSource = null; 
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    using (ErrorScreen ee = new ErrorScreen(ex.Message))
                                    {
                                        ee.ShowDialog();
                                    }
                                }
                            }
                            else
                            {
                                grdPhieuTraHang.DisplayLayout.Bands[0].Override.AllowDelete= DefaultableBoolean.False;
                            }

                        }
                    }
            }

        }
        private void grdPhieuTraHang_AfterSelectChange(object sender, AfterSelectChangeEventArgs e)
        {
            grdPhieuTraHang_ClickCell(null, null);
        }
        #endregion
        #endregion
        #region "Events "
        private void frmTraHang_Load(object sender, EventArgs e)
        {

            dtNgayTra.DateTime = DateTime.Now;
            this.WindowState = FormWindowState.Maximized;
        }
        private void frmTraHang_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Escape)
                this.Close();
            else if (e.KeyCode == Keys.F2)
            {
                if (tab == 1)
                {
                    if(btXuatLai.Enabled)
                    btXuatLai_Click(null, null);
                }
                else
                {
                    if (btnXuatPhieu.Enabled)
                        btnXuatPhieu_Click(null, null);
                }
            }
            else if (e.KeyCode == Keys.F12)
                btnHuy_Click(null, null);
            else if (e.KeyCode == Keys.F5)
                btSearchAll_Click(null, null);
        }
        private void ultraExTraHang_ItemClick(object sender, Infragistics.Win.UltraWinExplorerBar.ItemEventArgs e)
        {
            if (grdPhieu_TraKH_Chitiet.Rows.Count > 0)
            {
                using (ErrorScreen cfs = new ErrorScreen("Vui lòng xuất phiếu vừa nhập !","Thông báo",3))
                {
                    cfs.ShowDialog();
                    return;
                }
            }
            #region "Lập phiếu khách hàng trả hàng"
            if (ultraExTraHang.Groups["TraHangKH"].Items["LapPhieu"].Active)
            {

                tabTraHang.Tabs["LapPhieu"].Selected = true;
                LapPhieu_KhachHang();
            }
            #endregion
            #region "Lập phiếu trả hàng nhà cung cấp"
            if (ultraExTraHang.Groups["TraHangNCC"].Items["LapPhieu"].Active)
            {
                tabTraHang.Tabs["LapPhieu"].Selected = true;
                LapPhieu_NhaCungCap();
            }
            #endregion
            #region "Lịch sử khách hàng trả hàng"
            if (ultraExTraHang.Groups["TraHangKH"].Items["LichSu"].Active)
            {

                tabTraHang.Tabs["LichSu"].Selected = true;
                LoadLichSu_KhachHang();
            }
            #endregion
            #region "Lịch sử trả hàng nhà cung cấp"
            if (ultraExTraHang.Groups["TraHangNCC"].Items["LichSu"].Active)
            {

                tabTraHang.Tabs["LichSu"].Selected = true;
                LoadLichSu_NhaCungCap();
            }
            #endregion
        }
        private void tabTraHang_SelectedTabChanged(object sender, Infragistics.Win.UltraWinTabControl.SelectedTabChangedEventArgs e)
        {
            if (tabTraHang.Tabs["LapPhieu"].Selected == true)
            {
                
                tab = 0;
                if (DoiTuong == 1)
                    LapPhieu_NhaCungCap();
                else
                    LapPhieu_KhachHang();
            }
            else
            {
                tab = 1;
                this.SetControl_LichSu();
                if (DoiTuong == 1)
                    LoadLichSu_NhaCungCap();
                else
                    LoadLichSu_KhachHang();
            }
        }
        #endregion
       
    }
}